package com.cfc.stage1;

import org.junit.Test;

/**
 * @description: 最后一个单词的长度
 *   https://leetcode.cn/problems/length-of-last-word/
 * @author: yangxuan10
 * @create: 2024-04-19 10:17
 **/
public class LengthOfLastWord {

    @Test
    public void test1() {
        System.out.println(lengthOfLastWord("System out println"));
    }

    /**
     * 官方题解
     * @param s
     * @return
     */
    public int lengthOfLastWord1(String s) {
        int index = s.length() - 1;
        //先去掉末尾的空格
        while (s.charAt(index) == ' ') {
            index--;
        }
        int wordLength = 0;
        while (index >= 0 && s.charAt(index) != ' ') {
            wordLength++;
            index--;
        }
        return wordLength;
    }

    /**
     * 原创
     * @param s
     * @return
     */
    public int lengthOfLastWord(String s) {
        char [] chars = s.toCharArray();
        int wordLength = 0;
        for (int i = chars.length -1; i >=0 ;i--) {
            if (chars[i] != ' ') {
                wordLength ++;
            } else {
                //单词末尾可能有空格呢
                if (wordLength > 0) {
                    break;
                }
            }
        }
        return wordLength;
    }

}